package com.bw.xiaosy.shiro;

import com.bw.xiaosy.dao.UserInfoRepository;
import com.bw.xiaosy.dao.UserRoleRepository;
import com.bw.xiaosy.domain.UserInfo;
import com.bw.xiaosy.domain.UserRole;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 鉴权方法
 *
 * @author Xiaosy
 * @date 2017-04-06 14:50
 */
@Service
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限认证doGetAuthorizationInfo()");
        String username = (String) super.getAvailablePrincipal(principalCollection);
        System.out.println("username = " + username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        UserInfo userInfo = userInfoRepository.findByUsername(username);
        UserRole userRole = userRoleRepository.findByUserId(userInfo.getId());
        if(userRole.getRoleId() == 1) //admin
        {
            simpleAuthorizationInfo.addStringPermission("admin:listUser");
        }
        if(userRole.getRoleId() == 2)
        {
            simpleAuthorizationInfo.addStringPermission("test1:addUser");
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        UserInfo userInfo = userInfoRepository.findByUsername(username);
        if(userInfo == null)
        {
            //用户名错误
            throw new UnknownAccountException("用户名不存在");
        }
        if(!userInfo.getPassword().equals(password))
        {
            throw new IncorrectCredentialsException("密码不正确");
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,password,getName());
        return simpleAuthenticationInfo;
    }
}
